package com.tieto.user.ssl;

/**
 * SslSocketClient.java
 * Copyright (c) 2005 by Dr. Herong Yang
 * Before you execute this program, you have to prepare a jks file which will be trusted
 * by the client program. To make the trusted key store file you can use keytool -import command
 * You can read http://www.herongyang.com/JDK/SSL-Socket-Make-Self-Signed-Certificates-Trusted.html for more information.
 * This is also a good URL to study : http://docs.oracle.com/javaee/1.4/tutorial/doc/Security6.html
 */
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;

import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

// TODO change this to integration test case
// TODO refactor
public class SslSocketClient {
	public static void main(String[] args) {
		System.setProperty("javax.net.ssl.trustStore", "src/test/resources/user-management.jks");
		System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
		System.setProperty("javax.net.ssl.trustStoreType", "JKS");
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		PrintStream out = System.out;
		SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault();
		try {
			// This is the port number of the server on which server is
			// listening
			SSLSocket c = (SSLSocket) f.createSocket("localhost", 8443);
			printSocketInfo(c);
			c.startHandshake();
			BufferedWriter w = new BufferedWriter(new OutputStreamWriter(
					c.getOutputStream()));
			BufferedReader r = new BufferedReader(new InputStreamReader(
					c.getInputStream()));
			String m = null;
			while ((m = r.readLine()) != null) {
				out.println(m);
				m = in.readLine();
				w.write(m, 0, m.length());
				w.newLine();
				w.flush();
			}
			w.close();
			r.close();
			c.close();
		} catch (IOException e) {
			System.err.println(e.toString());
		}
	}

	private static void printSocketInfo(SSLSocket s) {
		System.out.println("Socket class: " + s.getClass());
		System.out.println("   Remote address = "
				+ s.getInetAddress().toString());
		System.out.println("   Remote port = " + s.getPort());
		System.out.println("   Local socket address = "
				+ s.getLocalSocketAddress().toString());
		System.out.println("   Local address = "
				+ s.getLocalAddress().toString());
		System.out.println("   Local port = " + s.getLocalPort());
		System.out.println("   Need client authentication = "
				+ s.getNeedClientAuth());
		SSLSession ss = s.getSession();
		System.out.println("   Cipher suite = " + ss.getCipherSuite());
		System.out.println("   Protocol = " + ss.getProtocol());
	}
}